const jwt = require('jsonwebtoken');
const helper = require('../../util/helper');
const config = require('../../config/environment/index');
const moment = require('moment');
const group = require('../../public/config/group');
const stringUtils = require("../../core/util/StringUtils");

exports.login = async (ctx) => {
    let userName = ctx.request.body.user_name || '',
        password = ctx.request.body.password || '';
    if (!userName || !password) {
        ctx.body = {
            result: 201,
            message: '用户名或密码不能为空'
        };
        return;
    }

    try {
        let results = await ctx.execSql.query(`SELECT manager_id, hash_password, salt ,group_id, role_id,role_name,role_description,login_count
     FROM v_manager_detail WHERE manager_name = ?`, userName);
        if (results.length > 0) {
            let hashedPassword = results[0].hash_password,
                salt = results[0].salt,
                hashPassword = helper.encryptPassword(password, salt);
            if (hashedPassword === hashPassword) {
                ctx.session.user = userName;
                // 用户token
                const userToken = {
                    name: userName,
                    id: results[0].manager_id
                };
                let groupId = (results[0].group_id <= 0 || results[0].group_id >= 6) ? 0 : group[results[0].group_id - 1].group_id;
                let groupName = (results[0].group_id <= 0 || results[0].group_id >= 6) ? '无' : group[results[0].group_id - 1].group_name;
                results[0].login_time = moment().format('YYYY-MM-DD HH:mm:ss');
                results[0].login_count++;
                await ctx.execSql.query(`UPDATE manager SET login_count = ?,login_time = ? WHERE manager_id = ?`, [results[0].login_count, results[0].login_time, results[0].manager_id]);
                // 签发token
                const token = jwt.sign(userToken, config.tokenSecret, {expiresIn: '4h'});
                ctx.body = {
                    result: 200,
                    token: token,
                    userName,
                    groupId,
                    groupName,
                    roleId:results[0].role_id,
                    roleName:results[0].role_name,
                    roleDescription:results[0].role_description,
                    count:results[0].login_count,
                    message: '登录成功'
                };
            } else {
                ctx.body = {
                    result: 201,
                    message: '用户名或密码错误'
                };
            }
        } else {
            ctx.body = {
                result: 201,
                message: '用户名或密码错误'
            };
        }
    } catch (error) {
        console.log(error);
        ctx.body = {
            result: 202,
            message: '查询数据出错'
        };
    }
}

exports.signOut = async (ctx) => {
    ctx.session.user = null;
    ctx.body = {
        result: 200,
        message: ''
    };
}




